// 订单智能分配模块
const { message } = window.antd;
const dayjs = window.dayjs;

// 订单状态枚举
const OrderStatus = {
    PENDING: 'pending',      // 待分配
    ASSIGNED: 'assigned',    // 已分配
    PROCESSING: 'processing',// 处理中
    COMPLETED: 'completed',  // 已完成
    EXCEPTION: 'exception'   // 异常
};

// 模拟订单数据
const mockOrders = [];

// 模拟店铺数据
const mockStores = [
    { id: 1, name: '总店', capacity: 50, currentLoad: 0, performance: 0.95 },
    { id: 2, name: '分店A', capacity: 30, currentLoad: 0, performance: 0.92 },
    { id: 3, name: '分店B', capacity: 40, currentLoad: 0, performance: 0.88 },
    { id: 4, name: '分店C', capacity: 25, currentLoad: 0, performance: 0.90 }
];

// 生成模拟订单
function generateMockOrder() {
    const orderId = 'ORD' + Date.now().toString().slice(-6);
    return {
        id: orderId,
        createTime: dayjs().toISOString(),
        status: OrderStatus.PENDING,
        priority: Math.random() > 0.8 ? 'high' : 'normal',
        estimatedProcessingTime: 15 + Math.floor(Math.random() * 10), // 15-25分钟
        assignedStore: null,
        assignTime: null,
        completionTime: null
    };
}

// 计算店铺评分
function calculateStoreScore(store, order) {
    const loadFactor = 1 - (store.currentLoad / store.capacity);
    const performanceFactor = store.performance;
    return loadFactor * 0.6 + performanceFactor * 0.4;
}

// 智能分配订单
function assignOrder(order) {
    try {
        // 按评分对店铺排序
        const rankedStores = mockStores
            .map(store => ({
                ...store,
                score: calculateStoreScore(store, order)
            }))
            .filter(store => store.currentLoad < store.capacity)
            .sort((a, b) => b.score - a.score);

        if (rankedStores.length === 0) {
            throw new Error('无可用店铺');
        }

        // 选择最优店铺
        const selectedStore = rankedStores[0];
        selectedStore.currentLoad++;

        // 更新订单信息
        order.status = OrderStatus.ASSIGNED;
        order.assignedStore = selectedStore.id;
        order.assignTime = dayjs().toISOString();

        return selectedStore;
    } catch (error) {
        console.error('订单分配失败:', error);
        order.status = OrderStatus.EXCEPTION;
        throw error;
    }
}

// 监控订单处理时效
function monitorOrderProcessing() {
    const now = dayjs();
    mockOrders.forEach(order => {
        if (order.status === OrderStatus.ASSIGNED || order.status === OrderStatus.PROCESSING) {
            const assignTime = dayjs(order.assignTime);
            const processingTime = now.diff(assignTime, 'minute');
            
            // 超过25分钟发出警告
            if (processingTime >= 25) {
                message.warning(`订单 ${order.id} 处理时间已达 ${processingTime} 分钟，即将超时！`);
            }
            
            // 超过30分钟标记为异常
            if (processingTime >= 30) {
                order.status = OrderStatus.EXCEPTION;
                message.error(`订单 ${order.id} 处理超时，已标记为异常！`);
            }
        }
    });
}

// 初始化订单分配系统
export function initOrderAssignment() {
    try {
        const contentWrapper = document.querySelector('.content-wrapper');
        contentWrapper.innerHTML = `
            <div class="order-assignment">
                <div class="assignment-header">
                    <h2>智能订单分配</h2>
                    <div class="control-panel">
                        <button id="generateOrder" class="btn-primary">生成测试订单</button>
                        <button id="toggleAutoAssign" class="btn-secondary">自动分配</button>
                    </div>
                </div>
                <div class="assignment-content">
                    <div class="orders-container">
                        <h3>订单列表</h3>
                        <div id="ordersList" class="orders-list"></div>
                    </div>
                    <div class="stores-container">
                        <h3>店铺状态</h3>
                        <div id="storesList" class="stores-list"></div>
                    </div>
                </div>
            </div>
        `;

        // 自动分配开关状态
        let autoAssignEnabled = false;
        let autoAssignInterval = null;

        // 更新订单列表显示
        function updateOrdersList() {
            const ordersList = document.getElementById('ordersList');
            if (!ordersList) return;

            ordersList.innerHTML = mockOrders
                .sort((a, b) => dayjs(b.createTime).diff(dayjs(a.createTime)))
                .map(order => {
                    const store = mockStores.find(s => s.id === order.assignedStore);
                    return `
                        <div class="order-item ${order.status}">
                            <div class="order-info">
                                <span class="order-id">${order.id}</span>
                                <span class="order-priority ${order.priority}">
                                    ${order.priority === 'high' ? '高优先级' : '普通'}
                                </span>
                                <span class="order-status">${order.status}</span>
                            </div>
                            <div class="order-details">
                                <span>创建时间: ${dayjs(order.createTime).format('HH:mm:ss')}</span>
                                ${store ? `<span>分配店铺: ${store.name}</span>` : ''}
                                ${order.assignTime ? 
                                    `<span>分配时间: ${dayjs(order.assignTime).format('HH:mm:ss')}</span>` : ''}
                            </div>
                        </div>
                    `;
                })
                .join('');
        }

        // 更新店铺状态显示
        function updateStoresList() {
            const storesList = document.getElementById('storesList');
            if (!storesList) return;

            storesList.innerHTML = mockStores
                .map(store => {
                    const loadPercentage = (store.currentLoad / store.capacity) * 100;
                    return `
                        <div class="store-item">
                            <div class="store-info">
                                <span class="store-name">${store.name}</span>
                                <span class="store-performance">
                                    绩效: ${(store.performance * 100).toFixed(0)}%
                                </span>
                            </div>
                            <div class="store-load">
                                <div class="load-bar">
                                    <div class="load-progress" style="width: ${loadPercentage}%"></div>
                                </div>
                                <span class="load-text">
                                    ${store.currentLoad}/${store.capacity}
                                </span>
                            </div>
                        </div>
                    `;
                })
                .join('');
        }

        // 生成测试订单按钮事件
        document.getElementById('generateOrder').addEventListener('click', () => {
            const newOrder = generateMockOrder();
            mockOrders.push(newOrder);
            updateOrdersList();

            // 如果开启了自动分配，立即尝试分配
            if (autoAssignEnabled) {
                try {
                    const store = assignOrder(newOrder);
                    message.success(`订单 ${newOrder.id} 已自动分配至 ${store.name}`);
                    updateOrdersList();
                    updateStoresList();
                } catch (error) {
                    message.error(`订单 ${newOrder.id} 自动分配失败`);
                }
            }
        });

        // 自动分配开关事件
        document.getElementById('toggleAutoAssign').addEventListener('click', function() {
            autoAssignEnabled = !autoAssignEnabled;
            this.classList.toggle('active');
            this.textContent = autoAssignEnabled ? '关闭自动分配' : '自动分配';

            if (autoAssignEnabled) {
                // 启动自动分配
                autoAssignInterval = setInterval(() => {
                    const pendingOrders = mockOrders.filter(order => 
                        order.status === OrderStatus.PENDING
                    );

                    pendingOrders.forEach(order => {
                        try {
                            const store = assignOrder(order);
                            message.success(`订单 ${order.id} 已自动分配至 ${store.name}`);
                        } catch (error) {
                            message.error(`订单 ${order.id} 自动分配失败`);
                        }
                    });

                    updateOrdersList();
                    updateStoresList();
                }, 5000); // 每5秒检查一次

                message.success('自动分配已开启');
            } else {
                // 关闭自动分配
                if (autoAssignInterval) {
                    clearInterval(autoAssignInterval);
                    autoAssignInterval = null;
                }
                message.info('自动分配已关闭');
            }
        });

        // 启动订单处理时效监控
        setInterval(monitorOrderProcessing, 60000); // 每分钟检查一次

        // 初始化显示
        updateOrdersList();
        updateStoresList();

    } catch (error) {
        console.error('初始化订单分配系统失败:', error);
        message.error('初始化订单分配系统失败，请刷新页面重试');
    }
}